package com.yuanhe.yunoj.judge.codeSandbox.strategy;

import cn.hutool.json.JSONUtil;
import com.yuanhe.yunoj.model.dto.question.JudgeCase;
import com.yuanhe.yunoj.model.dto.question.JudgeConfig;
import com.yuanhe.yunoj.model.dto.questionsubmit.JudgeInfo;
import com.yuanhe.yunoj.model.entity.Question;
import com.yuanhe.yunoj.model.enums.JudgeInfoMessageEnum;

import java.util.List;
import java.util.Optional;

public class DefaultJudgeStrategy implements JudgeStrategy {
    @Override
    public JudgeInfo dojudge(JudgeContext judgeContext) {
        // 5.根据沙箱的执行结果
        // 5.1先判断沙箱执行的结果输出数量是否和预期输出数量相等
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();

        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        Question question = judgeContext.getQuestion();
        Long memory = Optional.ofNullable(judgeInfo.getMemory()).orElse(0L);
        Long time = Optional.ofNullable(judgeInfo.getTime()).orElse(0L);

        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.ACCEPTED;
        JudgeInfo judgeInfoResponse = new JudgeInfo();

        judgeInfoResponse.setMemory(memory);
        judgeInfoResponse.setTime(time);
        if (inputList.size() != outputList.size()) {
             judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        // 5.2依次判断每一项输出和预期输出是否相等
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        for (int i = 0; i < judgeCaseList.size(); i++) {
            JudgeCase judgeCase = judgeCaseList.get(i);
            if (!judgeCase.getOutput().equals(outputList.get(i))) {
                judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
                return judgeInfoResponse;
            }
        }
        // 5.3判断题目限制
        String judgeConfig = question.getJudgeConfig();
        JudgeConfig needjudgeConfig = JSONUtil.toBean(judgeConfig, JudgeConfig.class);
        Long timeLimit = needjudgeConfig.getTimeLimit();
        Long memoryLimit = needjudgeConfig.getMemoryLimit();
        if (memoryLimit < memory) {
            judgeInfoMessageEnum = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        if (timeLimit < time) {
            judgeInfoMessageEnum = JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
        return judgeInfoResponse;
    }
}
